<?php
/**
 * Created by PhpStorm.
 * User: prg
 * Date: 2017/3/27
 * Time: 19:27
 */

// 管理员后台修改团队信息接口

require_once 'db.php';
require_once 'response.php';

header('content-type:text/html;charset:utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

//var_dump($_FILES);

$teamId = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
$img = !empty($_FILES['img']['tmp_name']) ? $_FILES['img'] : '';

//var_dump($_FILES['img']['tmp_name']);
//exit();

if(!is_numeric($teamId) || empty($name) || empty($content)) {
    return Response::show(401,'数据不合法');
}

try{
    $connect = Db::getInstance()->connect();
} catch (Exception $e) {
    return Response::show(403,'数据库连接失败');
}

$sql = "SELECT team_img FROM team WHERE team_id={$teamId}";
$res = $connect->query($sql);

$data = array(
    'IsUpdate' => false
);

if($res && $res->num_rows>0) {
    $old = $res->fetch_row();
    $res->free_result();

    // 分为有上传图片和没有上传图片来做处理
    if(empty($img)) {
//        echo 'no picture';
        $sql = "UPDATE team SET team_name=?,team_content=? WHERE team_id={$teamId}";
        $mysqli_stmt = $connect->prepare($sql);
        $mysqli_stmt->bind_param('ss',$name,$content);

        if($mysqli_stmt->execute()) {
            $data['IsUpdate'] = true;
            if($mysqli_stmt->affected_rows == 1) {
                return Response::show(200,'团队信息修改成功，图片未改变',$data);
            } else {
                return Response::show(402,'没有进行团队信息的更新',$data);
            }
        } else {
            return Response::show(403,'团队信息更新失败',$data);
        }
    } else {
//        echo 'picture';
        //判断文件上传的错误号
        if($img['error']>0) {
            //匹配错误信息
            $mes = '';
            switch ($img['error']){
                case 1:
                    $mes = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                    break;
                case 2:
                    $mes = '超过了表单MAX_FILE_SIZE限制的大小';
                    break;
                case 3:
                    $mes = '文件部分被上传';
                    break;
                case 4:
                    $mes = '没有选择上传文件';
                    break;
                case 6:
                    $mes = '没有找到临时目录';
                    break;
                case 7:
                case 8:
                    $mes = '系统错误';
            }
            //    exit($mes);
            $data['ImgFalseRes'] = $mes;
            return Response::show(400,'图片上传失败',$data);
        }

        //获得文件的扩展名
        $ext = pathinfo($img['name'],PATHINFO_EXTENSION);
        //规定允许上传的文件类型
        $allowExt = array('jpeg','jpg','png');
        if(!is_array($allowExt)) {
            //    exit('系统错误');
            $data['ImgFalseRes'] = '系统错误';
            return Response::show(400,'图片上传失败',$data);
        }
        //检测上传文件的类型
        if(!in_array($ext,$allowExt)) {
        //    exit('非法文件类型');
            $data['ImgFalseRes'] = '非法文件类型';
            return Response::show(400,'图片上传失败',$data);
        }

        $maxSize  = '2097152'; //2G
        //检测上传文件大小
        if($img['size']>$maxSize) {
        //    exit('上传文件过大');
            $data['ImgFalseRes'] = '上传文件过大';
            return Response::show(400,'图片上传失败',$data);
        }

        //    检测图片是否为真实的图片类型
        if(!getimagesize($img['tmp_name'])) {
        //    exit('不是真实的图片类型');
            $data['ImgFalseRes'] = '不是真实的图片类型';
            return Response::show(400,'图片上传失败',$data);
        }

        //检测文件是否通过HTTP POST方式上传上来
        if(!is_uploaded_file($img['tmp_name'])) {
        //    exit('文件不是通过HTTP POST方式上传上来的');
            $data['ImgFalseRes'] = '文件不是通过HTTP POST方式上传上来的';
            return Response::show(400,'图片上传失败',$data);
        }

        //进行文件的移动
        $uploadPath = 'uploads';
        if(!file_exists($uploadPath)) {
            mkdir($uploadPath,0777,true);
            chmod($uploadPath,0777);
        }
        //给文件进行命名，是根据时间生成一个唯一的文件名
        $uniName = md5(uniqid(microtime(true),true)).'.'.$ext;
        $destination = $uploadPath.'/'.$uniName;

        if(!@move_uploaded_file($img['tmp_name'],$destination)) {
            //    exit('文件移动失败');
            $data['ImgFalseRes'] = '文件移动失败';
            return Response::show(400,'图片上传失败',$data);
        }

        //通过验证并且移动图片之后，将新的图片入库，顺手删除掉原来的图片
        $sql = "UPDATE team SET team_name=?,team_content=?,team_img=? WHERE team_id={$teamId}";
        $mysqli_stmt = $connect->prepare($sql);
        $mysqli_stmt->bind_param('sss',$name,$content,$destination);

        if($mysqli_stmt->execute()) {
            $data['IsUpdate'] = true;
            @unlink("./".$old[0]);
            return Response::show(200,'团队信息上传成功',$data);
        } else {
            return Response::show(405,'图片已经上传服务器，新的团队信息插入失败',$data);
        }

    } // end of $img

} else {
    return Response::show(404,'找不到对应的团队信息',$data);
} // end of select


